package com.kmstech.greeting.web.servlets;

import java.io.IOException;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kmstech.greeting.entities.Greeting;
import com.kmstech.greeting.services.GreetingService;

public class GreetingServlet extends HttpServlet {
  private static final long serialVersionUID = 20110714L;
  
  @EJB
  private GreetingService _greetingService;

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    
    String language = req.getParameter("lang");
    if (language != null) {
      String message = _greetingService.getGreeting(language);
      req.setAttribute("language", language);
      req.setAttribute("message", message);
    }
    
    List<Greeting> greetings = _greetingService.getGreetings();
    req.setAttribute("greetings", greetings);

    forwardToJsp(req, resp, "/WEB-INF/jsp/greeting.jsp");
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String language = req.getParameter("language");
    String message = req.getParameter("message");

    try {
      _greetingService.addGreeting(language, message);

      // redirect to home page
      resp.sendRedirect(getServletContext().getContextPath());
    }
    catch (IllegalArgumentException ex) {
      req.setAttribute("error", ex.getMessage());
      forwardToJsp(req, resp, "/WEB-INF/jsps/greeting.jsp");
    }
  }
  
  private void forwardToJsp(HttpServletRequest req, HttpServletResponse resp,
      String jspPath) throws IOException, ServletException {
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(
        jspPath);
    dispatcher.forward(req, resp);
  }
}
